const BASE_URL = 'http://192.168.11.4:5000';

Page({
  data: {
    activeTab: 'account', // 'account' or 'sms'
    isAgree: false,
    showModal: false,
    modalTitle: '',
    modalContent: '',
    formData: {
      account: '',
      password: '',
      phone: '',
      code: ''
    },
    countdown: 0,
    loading: false
  },

  // 切换登录方式
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    if (tab !== this.data.activeTab) {
      this.setData({ 
        activeTab: tab,
        'formData.account': '',
        'formData.password': '',
        'formData.phone': '',
        'formData.code': '',
        countdown: 0
      });
    }
  },

  // 输入框变化
  onInputChange(e) {
    const field = e.currentTarget.dataset.field;
    this.setData({
      [`formData.${field}`]: e.detail.value
    });
  },

  // 发送验证码
  onSendCode() {
    if (this.data.countdown > 0) return;
    
    const phone = this.data.formData.phone.trim();
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({ title: '请输入正确手机号', icon: 'none' });
      return;
    }
    
    this.setData({ loading: true });
    wx.request({
      url: BASE_URL + '/api/send_sms',
      method: 'POST',
      data: { phone },
      header: { 'content-type': 'application/json' },
      success: (res) => {
        this.setData({ loading: false });
        if (res.data.code === 200) {
          wx.showToast({ title: '验证码已发送', icon: 'success' });
          this.startCountdown();
        } else {
          wx.showToast({ title: res.data.msg || '发送失败', icon: 'none' });
        }
      },
      fail: () => {
        this.setData({ loading: false });
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  // 开始倒计时
  startCountdown() {
    this.setData({ countdown: 60 });
    const timer = setInterval(() => {
      this.setData({
        countdown: this.data.countdown - 1
      });
      
      if (this.data.countdown <= 0) {
        clearInterval(timer);
      }
    }, 1000);
  },

  // 忘记密码
  onForgetPassword() {
    wx.showToast({
      title: '请联系客服重置密码',
      icon: 'none'
    });
  },

  // 账号密码登录
  onLogin() {
    if (!this.data.isAgree) {
      wx.showToast({ title: '请先阅读并同意协议', icon: 'none' });
      return;
    }
    
    if (this.data.activeTab === 'account') {
      this.loginWithPassword();
    } else {
      this.loginWithCode();
    }
  },

  // 密码登录
  loginWithPassword() {
    const { account, password } = this.data.formData;
    if (!account.trim() || !password.trim()) {
      wx.showToast({ title: '请输入账号和密码', icon: 'none' }); 
      return;
    }
    
    this.setData({ loading: true });
    wx.request({
      url: BASE_URL + '/api/login/password',
      method: 'POST',
      header: { 'content-type': 'application/json' },
      data: { 
        identifier: account.trim(), 
        password: password.trim() 
      },
      success: (res) => {
        this.setData({ loading: false });
        this.handleLoginResponse(res);
      },
      fail: () => {
        this.setData({ loading: false });
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  // 验证码登录
  loginWithCode() {
    const { phone, code } = this.data.formData;
    if (!phone.trim()) {
      wx.showToast({ title: '请输入手机号', icon: 'none' }); 
      return;
    }
    if (!/^\d{6}$/.test(code.trim())) {
      wx.showToast({ title: '请输入6位验证码', icon: 'none' }); 
      return;
    }
    
    this.setData({ loading: true });
    wx.request({
      url: BASE_URL + '/api/login_with_phone',
      method: 'POST',
      data: { 
        phone: phone.trim(), 
        code: code.trim() 
      },
      header: { 'content-type': 'application/json' },
      success: (res) => {
        this.setData({ loading: false });
        this.handleLoginResponse(res);
      },
      fail: () => {
        this.setData({ loading: false });
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },

  // 处理登录响应
  handleLoginResponse(res) {
    if (res.data.code === 200) {
      wx.setStorageSync('access_token', res.data.data.access_token);
      wx.setStorageSync('refresh_token', res.data.data.refresh_token);
      wx.showToast({ title: '登录成功', icon: 'success' });
      setTimeout(() => {
        wx.reLaunch({ url: '/pages/index/index' });
      }, 500);
    } else {
      wx.showToast({ title: res.data.msg || '登录失败', icon: 'none' });
    }
  },

  // 切换协议勾选状态
  toggleAgree() {
    this.setData({
      isAgree: !this.data.isAgree
    });
  },

  // 显示协议内容
  showAgreement(e) {
    const type = e.currentTarget.dataset.type;
    let title = '';
    let content = '';
    
    if (type === 'user') {
      title = '用户协议';
      content = '这里是用户协议的具体内容...\n\n1. 用户应遵守国家法律法规\n2. 不得发布违法信息\n3. 尊重他人隐私\n4. 其他条款...';
    } else {
      title = '隐私政策';
      content = '这里是隐私政策的具体内容...\n\n1. 我们如何收集和使用您的个人信息\n2. 我们如何存储和保护您的个人信息\n3. 您的权利\n4. 其他条款...';
    }
    
    this.setData({
      showModal: true,
      modalTitle: title,
      modalContent: content
    });
  },

  // 隐藏协议弹窗
  hideModal() {
    this.setData({ showModal: false });
  }
});